<template>
  <div class="dashboard-view">
    <el-row :gutter="10">
      <el-col :span="6">
        <el-card></el-card>
      </el-col>
      <el-col :span="18">
        <el-card></el-card>
      </el-col>
    </el-row>
    <el-row :gutter="10" style="margin-top: 20px">
      <el-col :span="8">
        <el-card>
          <z-chart ref="costBarChart" :resizable="true" />
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card style="position: relative; z-index: 99">
          <z-chart ref="userLineChart" />
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card>
          <z-chart ref="salePieChart" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import ZChart from "../components/chart/ZChart";
import dayjs from "dayjs";

export default {
  name: "DashboardView",
  components: { ZChart },
  data() {
    return {
      timer: null,
      allowPolling: false,
    };
  },
  methods: {
    // 绘制 柱形图
    async drawCostBar() {
      // 获取DOM元素
      const chart = this.$refs.costBarChart;
      const result = await this.$api.getCostData();
      // 把请求回来的数据 提取出 key(时间戳的格式) 作为 x轴 引入 dayjs做时间戳的转换

      chart.setOption({
        title: {
          text: "收入与支出",
        },
        legend: {
          data: ["收入", "支出"],
          right: 0,
        },
        grid: {
          left: "60px",
          right: "40px",
        },
        xAxis: {
          data: Object.keys(result).map((item) =>
            dayjs(Number(item)).format("YYYY-MM-DD")
          ),
        },
        yAxis: {},
        // 数据集
        series: [
          {
            name: "收入",
            data: Object.values(result).map((item) => item.earn),
            type: "bar",
          },
          {
            name: "支出",
            data: Object.values(result).map((item) => item.cost),
            type: "line",
          },
        ],
      });
    },
    //绘制 饼形图
    async drawSalePie() {
      const chart = this.$refs["salePieChart"];
      const result = await this.$api.getSaleData();
      const data = Object.entries(result)
        .map((item) => ({
          name: item[0],
          value: item[1],
          timer: null,
        }))
        .sort((a, b) => b.value - a.value)
        .slice(0, 5);
      const legendData = data.map((item) => item.name);
      chart.setOption({
        title: {
          text: "销售TOP5",
        },
        //配置颜色
        color: ["red", "orange", "orangered", "green", "purple"],
        // tooltip:鼠标移上去显示 信息
        tooltip: {},
        // 图示
        legend: {
          data: legendData,
          top: 30,
        },
        series: [
          {
            type: "pie",
            labelLine: {
              show: false,
            },
            bottom: 20,
            label: {
              show: false,
            },
            emphasis: {
              //emphasis：强调， 也是鼠标上去显示文字，把标签显示出来
              label: { show: true },
            },
            // 饼图的中心（圆心）坐标，数组的第一项是横坐标，第二项是纵坐标。支持设置成百分比，设置成百分比时第一项是相对于容器宽度，第二项是相对于容器高度。
            center: ["50%", "70%"],
            data: data,
          },
        ],
      });
    },
    //绘制线形图
    async drawUserLine() {
      const chart = this.$refs["userLineChart"];
      const result = await this.$api.getUserData();
      const xData = Object.keys(result).map((item) =>
        dayjs(Number(item)).format("HH:mm:ss")
      );
      const increaseData = Object.entries(result).map((item) =>
        Number(item[1].increase)
      );
      const onLineData = Object.entries(result).map((item) =>
        Number(item[1].online)
      );
      const totalData = Object.entries(result).map(
        (item) => Number(item[1].total) / 10000
      );
      // console.log("increaseData", increaseData);
      // console.log("onLineData", onLineData);
      // console.log("totalData", totalData);
      chart.setOption({
        title: {
          text: "用户相关",
        },
        xAxis: {
          data: xData,
        },
        tooltip: {
          show: true,
          trigger: "axis",
        },
        yAxis: {
          data: totalData.forEach((item) => Number(item)),
        },
        grid: {
          left: 40,
          right: 20,
          bottom: 18,
          z: 99,
        },
        legend: {
          data: ["用户增长数", "在线人数", "总注册人数(w)"],
          top: 30,
        },
        series: [
          {
            name: "用户增长数",
            data: increaseData,
            type: "line",
            smooth: true,
          },
          {
            name: "在线人数",
            data: onLineData,
            type: "line",
            smooth: true,
          },
          {
            name: "总注册人数(w)",
            data: totalData,
            type: "line",
            smooth: true,
          },
        ],
      });
    },

    // 轮询方法
    polling() {
      if (!this.allowPolling) return;
      clearTimeout(this.timer);
      this.timer = setTimeout(async () => {
        try {
          await this.drawUserLine();
          this.polling(); // 递归
        } catch (e) {
          this.endPolling();
        }
      }, 2000);
    },
    // 开启轮询
    startPolling() {
      this.allowPolling = true;
      this.polling();
    },
    // 结束轮询
    endPolling() {
      clearTimeout(this.timer);
      this.timer = null;
      this.allowPolling = false;
    },
  },
  mounted() {
    //   调用绘制方法
    this.drawCostBar();
    this.drawSalePie();
    //轮询 绘制 用户相关 的echart
    this.startPolling();
  },
  //   组件销毁前 关闭轮询
  beforeDestroy() {
    this.endPolling();
  },
  //组件 重新激活 开始轮询
  activated() {
    this.startPolling();
  },
  // 组件失活 关闭轮询
  deactivated() {
    this.endPolling();
  },
};
</script>

<style lang="scss" scoped>
.el-card ::v-deep.el-card__body {
  box-sizing: border-box;
  height: 280px;
}
</style>
